package com.example.controller;

import cn.hutool.core.date.DateUtil;
import com.example.bean.Comment;
import com.example.service.CommentService;
import com.example.until.Result;
import com.example.until.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @title: Comment
 * @Author wjf
 * @Date: 2022/10/2 14:48
 * @Version 1.0
 */
@RestController
@CrossOrigin
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @GetMapping("/{articleId}/{bookId}")
    public Result getComments(@PathVariable(required = false) Integer articleId, @PathVariable(required = false) Integer bookId){
        // 查询所有的评论和回复数据
        List<Comment> commentList = commentService.getComments(articleId,bookId);
        // 查询评论数据(不包括回复)
        List<Comment> originList = commentList.stream().filter(comment -> comment.getOriginId() == null).collect(Collectors.toList());

        // 设置评论数据的子节点，也就是回复内容
        for (Comment origin:originList){
            List<Comment> comments = commentList.stream().filter(comment -> origin.getId().equals(comment.getOriginId())).collect(Collectors.toList());
            comments.forEach(comment -> {
                Optional<Comment> pComment = commentList.stream().filter(c -> c.getId().equals(comment.getPid())).findFirst();  //找到当前评论分父级
                pComment.ifPresent((v->{     // 找到父级评论的用户id和用户昵称，并设置给当前的回复对象
                    comment.setPUserId(v.getUserId());
                    comment.setPNickname(v.getNickname());
                }));
            });
            origin.setChildren(comments);
        }
        return Result.ok(originList) ;
    }

    @PostMapping("/save")
    public Result saveComment(@RequestBody Comment comment){
        if (comment.getId() == null){  //新增评论
            comment.setUserId(TokenUtils.getCurrentUser().getId());
            comment.setTime(DateUtil.now());
        }
        if (comment.getPid()!=null){   //判断如果是回复，进行处理
            Integer pid = comment.getPid();
            Comment pComment = commentService.getById(pid);
            if (pComment.getOriginId()!=null){  //如果当前回复的父级有祖宗，那么就设置相同的祖宗
                comment.setOriginId(pComment.getOriginId());
            }else {  //否则就设置父级为当前回复的祖宗
                comment.setOriginId(comment.getPid());
            }
        }
        boolean save = commentService.saveOrUpdate(comment);
        return Result.ok(save);
    }

    @DeleteMapping("/{id}")
    public Result deleteComment(@PathVariable Integer id){
        boolean b = commentService.removeById(id);
        return Result.ok(b);
    }
}
